package com.fz.song.resolver;


import com.alibaba.fastjson.JSON;
import com.fz.song.enums.ExceptionEnum;
import com.fz.song.exception.CustomException;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class MyHandlerException implements HandlerExceptionResolver {

    private static final Logger logger = LogManager.getLogger(MyHandlerException.class);


    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        logger.error("服务器出错", ex);

        CustomException exception = null;
        if (ex instanceof CustomException) {
            exception = (CustomException) ex;
        } else {
            exception = new CustomException(ExceptionEnum.SYSTEM_ERROR.getCode(), ExceptionEnum.SYSTEM_ERROR.getMessage());
        }
        int code = exception.getCode();
        String message = exception.getMessage();

        //如果是ajax请求，就返回一个json格式的出错提示信息
        if (request.getHeader("X-Requested-With") != null) {
            try {

                Map<String, Object> map = new HashMap();
                map.put("code", code);
                map.put("message", message);
                String json = JSON.toJSONString(map);
                response.getWriter().println(json);
            } catch (IOException e) {
                logger.error("服务器失败时发送错误提示信息失败", e);
            }
            return new ModelAndView();
        } else {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("error");
            modelAndView.addObject("code",code);
            modelAndView.addObject("message",message);

            return modelAndView;
        }
    }
}


